package com.ship.dispatch.controller.shipReport;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ship.common.core.base.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.FileUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.decisionAnalysis.SmShipRent;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bean.shipBusiness.SmShipReport;
import com.ship.dispatch.bean.shipBusiness.SmThirdPartyMeasure;
import com.ship.dispatch.model.dto.shipReport.ThirdPartyMeasureDto;
import com.ship.dispatch.service.ExportService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.shipBusiness.SmThirdPartyMeasureService;
import com.ship.dispatch.vo.shipReport.ThirdPartyMeasureDetailAllVo;
import com.ship.dispatch.vo.shipReport.ThirdPartyMeasureDetailVo;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/thirdParty/")
@Api(value = "thirdParty", tags = "船务管理（第三方计量）")
public class ThirdPartyMeasureController {
    @Autowired
    private SmThirdPartyMeasureService thirdPartyMeasureService;
    @Autowired
    SpFobFileRecordService spFobFileRecordService;
    @Autowired
    private ExportService exportService;
    @Value("${file_server.host}")
    private String fileServerHost;
    private static final String FILE_UPLOAD_PATH = "/group1/upload";

    @Value("${third_party_measure_template_url}")
    private String templateUrl;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 船务管理（第三方计量）分页
     *
     * @param thirdPartyMeasure
     * @return
     */
    @ApiOperation(value = "船务管理（第三方计量）分页")
    @PostMapping("page")
    public JsonResult<Page<SmThirdPartyMeasure>> page(@RequestBody SmThirdPartyMeasure thirdPartyMeasure) {
        Page<SmThirdPartyMeasure> page = thirdPartyMeasureService.page(thirdPartyMeasure, new QueryWrapper<>());
        return JsonResult.success(page);
    }

    /**
     * 船务管理-第三方计量详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "船务管理-第三方计量详情")
    @GetMapping("selectThirdPartyMeasureDetail/{id}")
    public JsonResult selectThirdPartyMeasureDetail(@PathVariable Long id) {
        List<SpFobFileRecord> fileRecords = spFobFileRecordService.list(new LambdaQueryWrapper<SpFobFileRecord>()
                .eq(SpFobFileRecord::getThirdPartyMeasureId, id));
        ThirdPartyMeasureDetailAllVo detailVoList = thirdPartyMeasureService.selectThirdPartyMeasureDetail(id, fileRecords);
        return JsonResult.success(detailVoList);
    }

    /**
     * 上传船务管理第三方计量附件
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "上传船务管理第三方计量附件")
    @PostMapping("uploadThirdPartyMeasure")
    @Log(title = "上传船务管理第三方计量附件", businessType = BusinessType.IMPORT)
    public JsonResult uploadThirdPartyMeasure(@RequestParam("file") MultipartFile file
            , @RequestParam("id") Long id) {
        FileUtils.checkFileName(file);
        try {
            String url = "";
            String name = file.getOriginalFilename();
            url = upload(file);
            SpFobFileRecord spFobFileRecord = new SpFobFileRecord();
            spFobFileRecord.setPath(url);
            spFobFileRecord.setName(name);
            spFobFileRecord.setFileType("船务管理第三方计量");
            spFobFileRecord.setThirdPartyMeasureId(id);
            spFobFileRecord.setCreateDate(new Date());
            spFobFileRecord.setCreateBy(SecurityUtils.getStringUserId());
            spFobFileRecordService.save(spFobFileRecord);
            return JsonResult.success(spFobFileRecord.getId().toString());
        } catch (Exception e) {
            return JsonResult.failed("上传失败，原因：" + e.getMessage());
        }
    }

    /**
     * 保存船务管理第三方计量备注
     *
     * @param thirdPartyMeasureDto
     * @return
     */
    @ApiOperation(value = "保存船务管理第三方计量备注")
    @PostMapping("uploadThirdPartyMeasureRemarks")
    @Log(title = "保存船务管理第三方计量备注", businessType = BusinessType.INSERT)
    public JsonResult uploadThirdPartyMeasureRemarks(@RequestBody ThirdPartyMeasureDto thirdPartyMeasureDto) {
        if (null != thirdPartyMeasureDto.getId()) {
            SmThirdPartyMeasure thirdPartyMeasure = thirdPartyMeasureService.getById(thirdPartyMeasureDto.getId());
            if (null != thirdPartyMeasure) {
                thirdPartyMeasure.setRemarkContent(thirdPartyMeasureDto.getRemarkContent());
                thirdPartyMeasureService.updateById(thirdPartyMeasure);
            }
        }
        return JsonResult.success();
    }

    /**
     * 上传附件M
     *
     * @return
     */
    public String upload(MultipartFile file){
        FileUtils.checkFileName(file);
        R<SysFile> result1 = remoteFileService.upload(file);
        if(result1.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String result = result1.getData().getHttpsUrl();;
        return result;
    }

    /**
     * 删除船务管理第三方计量附件
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除船务管理第三方计量附件")
    @DeleteMapping("/deleteFile/{id}")
    @Log(title = "删除船务管理第三方计量附件", businessType = BusinessType.DELETE)
    public JsonResult deleteFile(@PathVariable("id") Long id) {
        spFobFileRecordService.removeById(id);
        return JsonResult.success();
    }

    /**
     * 船务管理第三方计量列表导出
     *
     * @return
     */
    @ApiOperation(value = "船务管理第三方计量列表导出")
    @PostMapping("page/export")
    @Log(title = "船务管理第三方计量列表导出", businessType = BusinessType.EXPORT)
    public JsonResult pageExport(@RequestBody SmThirdPartyMeasure thirdPartyMeasure) {
        //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (thirdPartyMeasure.getIds() != null && thirdPartyMeasure.getIds().size() > 0) {
            queryWrapper.in("id", thirdPartyMeasure.getIds());
        }
        List<SmThirdPartyMeasure> exportList = thirdPartyMeasureService.pageExportList(thirdPartyMeasure, queryWrapper, new LinkedList<>());
//        for (SmThirdPartyMeasure smThirdPartyMeasure : exportList) {
//
//        }
        Field[] fields = SmThirdPartyMeasure.class.getDeclaredFields();
        String url = exportService.pageExport(exportList, fields, exportService.listStrByModuleAndUser
                ("sm_third_party_measure", SecurityUtils.getUserId()), "第三方计量报告-");
        return JsonResult.success(url);
    }

    /**
     * 船务管理-第三方计量详情导出
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "船务管理-第三方计量详情导出")
    @GetMapping("exportThirdPartyMeasureDetail/{id}")
    public JsonResult exportThirdPartyMeasureDetail(@PathVariable Long id) {
        List<SpFobFileRecord> fileRecords = spFobFileRecordService.list(new LambdaQueryWrapper<SpFobFileRecord>()
                .eq(SpFobFileRecord::getThirdPartyMeasureId, id));
        JsonResult exportThirdPartyMeasureDetail = thirdPartyMeasureService.exportThirdPartyMeasureDetail(templateUrl,id, fileRecords,fileServerHost);
        return exportThirdPartyMeasureDetail;
    }

    /**
     * 船务管理第三方计量列表详情导出
     *
     * @return
     */
    @ApiOperation(value = "船务管理第三方计量列表详情导出")
    @PostMapping("page/exportAll")
    @Log(title = "船务管理第三方计量列表详情导出", businessType = BusinessType.EXPORT)
    public JsonResult pageExportAll(@RequestBody SmThirdPartyMeasure thirdPartyMeasure) throws IOException {
        JsonResult result = new JsonResult();
        List<SpFobFileRecord> fileRecords = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        QueryWrapper queryWrapper = new QueryWrapper<>();
        if (thirdPartyMeasure.getIds() != null && thirdPartyMeasure.getIds().size() > 0) {
            queryWrapper.in("id", thirdPartyMeasure.getIds());
            fileRecords = spFobFileRecordService.list(new LambdaQueryWrapper<SpFobFileRecord>()
                    .in(SpFobFileRecord::getThirdPartyMeasureId, thirdPartyMeasure.getIds()));
        }
        List<SmThirdPartyMeasure> exportList = thirdPartyMeasureService.pageExportList(thirdPartyMeasure, queryWrapper, new LinkedList<>());
//        for (SmThirdPartyMeasure smThirdPartyMeasure : exportList) {
//
//        }
        String listName = "第三方计量报告-" + dateFormat.format(new Date());
        Field[] fields = SmThirdPartyMeasure.class.getDeclaredFields();
        String url = exportService.pageMergeExport(exportList, fields, exportService.listStrByModuleAndUser
                ("sm_third_party_measure", SecurityUtils.getUserId()), "thirdPartyList");

        if(StringUtils.isNotEmpty(url)){
            String urlNew = url.split("\\?")[0].toString();
            result = thirdPartyMeasureService.pageExportAll(templateUrl,thirdPartyMeasure.getIds(),fileRecords,fileServerHost,urlNew,listName);
        }
        return result;
    }
}
